<template>
    <view>
        <view class="main" v-if="isShow">
            <view class="card">
                <view class="title" v-if="storeIds.length <= 0">默认设置</view>
                <view class="title" v-else-if="storeIds.length == 1">场地: {{store.storeName}}</view>
                <view class="title" v-else-if="storeIds.length > 1">你正在对
                    <text class="count">{{storeIds.length}}</text>
                    个场地进行客服微信的设置
                </view>
                <view class="wechat-name">
                    <view>客服名称（仅限8个字）</view>
                    <view class="inputbg">
                        <u-input v-model="customerServiceInfo.serviceName" type="text" maxlength="8" :border="false"
                                 class="wechat-number-input" :custom-style="{'padding':'5rpx 20rpx'}" :clearable="true"
                                 placeholder="请输入客服名称(仅限8个字)" fontSize="28rpx"/>
                    </view>
                </view>
                <u-line></u-line>

                <view class="wechat-number">
                    <view>客服微信号</view>
                    <view class="inputbg">
                        <u-input v-model="customerServiceInfo.serviceWeChatNumber" type="text" :border="false"
                                 class="wechat-number-input" :custom-style="{'padding':'5rpx 20rpx'}" :clearable="true"
                                 placeholder="请输入客服微信号" maxlength="20" fontSize="28rpx"/>
                    </view>
                </view>

                <view class="wechat-code">
                    <view>
                        <text>客服微信二维码</text>
                        <text class="standard" @click="isStandardShow=true">查看样式规范</text>
                    </view>
                    <view class="upload">
                        <u-upload
                            :fileList="fileList"
                            @afterRead="photoUploadAfterRead"
                            @delete="onRemoveBrandWechatImage"
                            name="image"
                            multiple
                            :maxCount="1"
                            @oversize="bannerOversize"
                        />
                        <view class="warning">
                            <text>
                              1、图片只能包含正方形的二维码
                              2、不能有其它信息或空白
                              3、请参考规范样例
                            </text>
                        </view>
                    </view>
                </view>
                <view class="wechat-number-warning">
                    <text>提醒: 客服微信号和客服微信二维码必须填写或选择至少一个</text>
                </view>
                <view class="btn">
                    <view>
                        <u-button type="primary" class="save" @click="submit">保存</u-button>
                    </view>
                    <text class="u-m-r-20"
                          v-if="param.serviceName != null || param.serviceWeChatNumber != null || param.serviceWeChatQr != null"
                          @click="clear">清除设置
                    </text>
                </view>
            </view>
        </view>
        <empty :emptyTitle="'暂无场地,请重新访问'" v-else></empty>
        <u-modal :show="isStandardShow" title="规范二维码图片" @confirm="isStandardShow=false">
            <view class="model">
                <u--image :src="`${baseStaticFileUrl}/image/brand/wechatQRCode.png`" width="500rpx" height="500rpx"/>
            </view>
        </u-modal>
    </view>
</template>

<script>
    import indexConfig from '@/common/config/config.js'

    export default {
        data() {
            return {
                isShow: false,
                storeIds: [],
                store: {},
                imgURL: this.$configPath.imgURL,
                baseStaticFileUrl: this.$configPath.staticFileUrl,
                uploadUrl: indexConfig.baseURL + '/api/upload/uploadImageToFTP',
                brandInfoId: 0,
                header: {
                    Authorization: '',
                },
                isStandardShow: false,
                customerServiceInfo: {
                    id: 0,
                    serviceName: '',
                    serviceWeChatNumber: '',
                    serviceWeChatQr: ''
                },
                param: {
                    id: 0,
                    serviceName: '',
                    serviceWeChatNumber: '',
                    serviceWeChatQr: ''
                },
                formerServiceWeChatQr: '',
                fileList: [],
                lists: [],
                batch: false,
                merchantInfoUploadStateEnum: this.$merchantInfoUploadStateEnum,
				storageKeyEnum: this.$storageKeyEnum,
            }
        },
        onLoad(param) {
			this.header.Authorization = 'Bearer ' + this.storageKeyEnum.token_cache;
            if (param.brandInfoId){
              this.isShow = true;
              this.findDefault();
            } else if (!this.$u.test.isEmpty(param.storeIds)) {
                this.storeIds = JSON.parse(param.storeIds);
                if (this.storeIds.length > 1) {
                    this.batch = true;
                    this.findDefault();
                } else {
                    this.findStore(this.storeIds[0]);
                }
                this.isShow = true;
            } else {
              getApp().err("读取参数不成功，请重新进入页面");
            }
        },

        methods: {
            findStore(id) {
                uni.showLoading({
                    title: '请稍等...',
                    mask: true
                })
                this.$api('merchantStore.findMerchantStoreByUserIdByStoreId', {
                    id: id
                }).then(res => {
                    this.store = res.data;
                    if (this.store != null) {
                        this.findByMerchantStoreId(id);
                    } else {
                        uni.hideLoading();
                        getApp().err("访问失败!请重新访问!");
                        return;
                    }
                })
            },
            findByMerchantStoreId(merchantStoreId) {
                this.fileList = [];
                this.lists = [];
                this.$api('customerServiceInfo.findByMerchantStoreId', {
                    merchantStoreId: merchantStoreId
                }).then(res => {
                    uni.hideLoading();
                    this.isShow = true;
                    if (res.data != null) {
                        this.customerServiceInfo = {
                            id: res.data.id,
                            serviceName: res.data.serviceName,
                            serviceWeChatNumber: res.data.serviceWeChatNumber,
                            serviceWeChatQr: res.data.serviceWeChatQr
                        };
                        this.param = JSON.parse(JSON.stringify(this.customerServiceInfo))
                        this.callBack(res);
                    }
                })
            },
            findDefault() {
                this.fileList = [];
                this.lists = [];
                uni.showLoading({
                    title: '请稍等...',
                    mask: true
                })
                this.$api('brandInfo.findByUserId').then(res => {
                    uni.hideLoading();
                    if (res.data == null) {
                        getApp().err("访问失败!请重新访问!");
                        return;
                    }
                    this.isShow = true;
                    this.customerServiceInfo = {
                        brandInfoId: res.data.id,
                        serviceName: res.data.serviceName,
                        serviceWeChatNumber: res.data.serviceWeChatNumber,
                        serviceWeChatQr: res.data.serviceWeChatQr
                    };
                    this.param = JSON.parse(JSON.stringify(this.customerServiceInfo));
                    this.callBack(res);
                })
            },
            callBack(res) {
                // 保存一下图片到旧的属性上
                this.formerServiceWeChatQr = res.data.serviceWeChatQr;
                if (res.data.serviceWeChatQr != null) {
                    this.fileList.push({
                        url: this.$configPath.imgURL + res.data.serviceWeChatQr
                    });
                    this.lists.push({
                        url: this.$configPath.imgURL + res.data.serviceWeChatQr
                    });
                }
            },
            async photoUploadAfterRead(event) {
                uni.showLoading({
                    title: '上传中',
                    mask: true
                })
                console.log("event", event)
                const fileUrl = event.file[0].url;
                const item = {
                    url: fileUrl,
                    status: 'uploading',
                    message: '上传中'
                }
              this.fileList.push(item);

                this.photoUploadFilePromise(fileUrl).then((res) => {
                    const url = this.imgURL.concat('/').concat(getApp().formatImageSuffix(res.data.keyRes));
                    this.fileList.splice(0, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: url
                    }))

                  this.customerServiceInfo.serviceWeChatQr = res.data.keyRes;
                }).catch((err) => {
                    console.error("brandWechatSet", err)
                    this.fileList.splice(0, 1);
                })
            },
            photoUploadFilePromise(fileUrl) {
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: this.$configPath.baseURL + '/api/upload/uploadImageToFTP',
                        filePath: fileUrl,
                        name: 'image',
                        header: {
                            Authorization: 'Bearer ' + this.$store.getters.GET_VALUE("GET_TOKEN")
                        },
                        timeout: 6000,
                        formData: {},
                        success: (res) => {
                            uni.hideLoading();
                            let data = JSON.parse(res.data);
                            if (this.merchantInfoUploadStateEnum.SUCCESS == data.status) {
                                this.$helpers.toast("上传成功", "success");
                                resolve(data);
                            } else if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == data.status){
                                //上传成功，识别失败
                                resolve(data);
                            } else {
                                reject(data)
                                getApp().err("上传不成功，" + data.msg);
                            }
                        },
                        fail: (res) => {
                            uni.hideLoading();
                            let errMsg = res.errMsg;
                            if (uni.$u.test.contains(errMsg, 'timeout')) {
                                errMsg = "请求超时，请重新上传";
                            }
                            getApp().err(errMsg);
                            reject("请求超时，请重新上传")
                        },
                    });
                })
            },
            submit() {
                if (this.$u.test.isEmpty(this.customerServiceInfo.serviceName)) {
                    getApp().err("请填写客服名称");
                    return;
                }
                if (this.customerServiceInfo.serviceName.length > 8) {
                    getApp().err("客服名称不能超过8个字");
                    return;
                }

                if (this.$u.test.isEmpty(this.customerServiceInfo.serviceWeChatNumber) && this.$u.test.isEmpty(this.customerServiceInfo.serviceWeChatQr)) {
                    getApp().err("客服微信号和客服微信二维码必须填写或选择至少一个");
                    return;
                }

                if (this.storeIds.length > 0) {
                    this.customerServiceInfo['storeIds'] = this.storeIds;
                }
                uni.showLoading({
                    title: '请稍等...',
                    mask: true
                })
                if (this.lists.length <= 0) {
                    this.edit();
                } else {
                    if (this.formerServiceWeChatQr == this.customerServiceInfo.serviceWeChatQr) {
                        this.edit();
                    }
                }
            },
            edit() {
                this.$api('customerServiceInfo.editWeChat', this.customerServiceInfo).then(res => {
                    uni.hideLoading();
                    if (res.status == 1) {
                        this.$helpers.toast(res.msg);
                        // 保存失败就把新的图片删除
                        this.deleteServiceWeChatQr(this.customerServiceInfo.serviceWeChatQr);
                    } else {
                        this.$helpers.toast('保存成功', 'success', 3000, true, () => {});
                        // 保存一下图片到旧的属性上
                        this.formerServiceWeChatQr = this.customerServiceInfo.serviceWeChatQr;
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: this.batch ? 2 : 1
                            });
                            uni.$emit('edit', "true")
                        }, 1000)
                    }
                }).catch(() => {
                    uni.hideLoading();
                    getApp().err("异常信息!请重新访问!");
                });
            },
            onRemoveBrandWechatImage() {
                this.lists = [];
                this.fileList = [];
                this.customerServiceInfo.serviceWeChatQr = '';
            },

            // 删除已上传的图片
            deleteServiceWeChatQr(serviceWeChatQr) {
                if (this.$u.test.isEmpty(serviceWeChatQr)) {
                    return;
                }
                let param = {
                    serviceWeChatQr: serviceWeChatQr,
                }
                this.$api('customerServiceInfo.deleteServiceWeChatQr', param)
                    .then(res => {
                        if (res.status == 0) {
                            console.log('删除成功');
                        } else {
                            console.log('删除失败');
                        }
                    })
            },

            bannerOversize() {
              getApp().err("图片大小超限，最大3MB。如图片来自相册，建议使用直接拍摄");
            },

            clear() {
                if (this.storeIds.length > 1) {
                    this2.$helpers.toast("清除失败,请重新访问此页面");
                    return;
                }
                let this2 = this;
                uni.showModal({
                    title: '提示',
                    content: '确定要清除并保存客服微信设置吗?',
                    success: function (res) {
                        if (res.confirm) {
                            uni.showLoading({
                                title: '请稍等...',
                                mask: true
                            })
                            this2.param.serviceName = null;
                            this2.param.serviceWeChatNumber = null;
                            this2.param.serviceWeChatQr = null;
                            if (this2.storeIds.length > 0) {
                                this2.param['storeIds'] = this2.storeIds;
                                this2.param.merchantStoreId = this2.storeIds[0];
                            }

                            this2.$api('customerServiceInfo.clearWeChat', this2.param).then(res => {
                                uni.hideLoading();
                                if (res.data > 0) {
                                    console.log(this2.formerServiceWeChatQr);
                                    if (this2.formerServiceWeChatQr != null && this2
                                        .formerServiceWeChatQr != '') {
                                        this2.deleteServiceWeChatQr(this2.formerServiceWeChatQr);
                                    }
                                    uni.showToast({
                                        title: "清除成功",
                                        mask: true
                                    })
                                    setTimeout(() => {
                                        uni.navigateBack({
                                            delta: this.batch ? 2 : 1
                                        });
                                        // uni.navigateBack({
                                        // 	delta: 1
                                        // });
                                        uni.$emit('edit', "true")

                                    }, 1000)
                                } else {
                                    this2.$helpers.toast("清除失败,请重新访问此页面");
                                }
                            })
                        }
                    }
                });
            }
        },
    }
</script>

<style lang="scss">
    page {
        background-color: $u-bg-color;
    }


	.main {
		padding: $u-padding-medium;
		color: rgba(0, 0, 0, 0.75);
		font-size: $f-base;
		.card {
			padding: $u-padding-medium;
			background-color: white;
			border-radius: $uni-border-radius-lg;

			.title {
				padding: $u-padding-mini 0;
				color: $u-tips-color;

				.count {
					color: grey;
				}
			}

			.inputbg {
				padding: 10rpx 0;
				margin-top: 20rpx;
				background-color: rgb(243, 244, 246);
				border-radius: 5rpx;
			}

			.wechat-name {
				margin: $u-margin-medium 0;
				font-size: $uni-font-size-lg;
				font-weight: 450;

				.wechat-number-input {
					// background-color: $u-bg-color;
					border-radius: $uni-border-radius-lg + 3;
					margin-top: 20rpx;
					font-weight: normal;
				}
			}

			.wechat-number-warning {
				margin-top: 20rpx;
				color: $u-tips-color;
				font-size: $uni-font-size-sm;
				background-color: rgb(236, 245, 255);
				padding: $u-padding-mini $u-padding-medium;
				border-radius: $uni-border-radius-lg - 2;
				line-height: 40rpx;
			}

			.wechat-number {
				margin: $u-margin-medium 0;
				font-size: $uni-font-size-lg;
				font-weight: 450;

				.wechat-number-input {
					background-color: $u-bg-color;
					border-radius: $uni-border-radius-lg + 3;
					margin-top: 20rpx;
					font-weight: normal;
				}
			}

			.wechat-code {
				margin-top: $u-margin-large;
				font-size: $uni-font-size-lg;
				font-weight: 450;

				.standard {
					font-weight: normal;
					font-size: $f-sm;
					color: $u-primary;
					margin-left: $u-margin-large;
				}

				.upload {
					display: flex;
					align-items: center;
					margin-top: $u-margin-medium;

					.upload-btn {
						width: 200rpx;
						height: 200rpx;
						overflow: hidden;
						margin: 10rpx;
						background: rgb(244, 245, 246);
						position: relative;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						flex-direction: column;
						color: $u-content-color;
						font-size: 26rpx;

						.u-add-tips {
							margin-top: 20rpx;
							line-height: 40rpx;
						}
					}

					.warning {
						color: $u-tips-color;
						font-size: $uni-font-size-sm;
						background-color: rgb(236, 245, 255);
						padding: $u-padding-medium;
						border-radius: $uni-border-radius-lg - 2;
						line-height: 40rpx;
					}
				}
			}

			.btn {
				display: flex;
				align-items: center;
				flex-direction: row-reverse;
				margin-top: $u-margin-large;
				color: $u-primary;
				font-size: $f-base;
				.preview {
					margin-left: $u-margin-large;
				}

				.save {
					margin-left: $u-margin-medium;
				}
			}
		}
	}

	.model {
		padding: $u-padding-large;
	}

	.popup {
		font-size: $f-base;
		padding-top: 80rpx;

		.popup-title {
			text-align: center;
			font-size: $f-lg;
			color: $u-tips-color;
			padding: $u-padding-large 0;
			font-weight: 450;
		}

		.img {
			display: flex;
			justify-content: center;
		}

		.preview-wechat-number {
			text-align: center;
			font-size: $f-lg;
			color: gray;
			padding: $u-padding-large 0;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

    /deep/ .u-upload__button {
      margin: 0rpx !important;
    }
</style>
